/**
 * @author		Sergey Suzdalskiy
 * @e-mail:		sergey.suzdalskiy@gmail.com
 */
package ua.kiev.gcore.ui.controls
{
	import flash.display.Sprite;
	import flash.geom.Point;
	
	import ua.kiev.gcore.ui.controls.gallery.Gallery;
	import ua.kiev.gcore.ui.controls.gallery.GalleryFilter;
	
	public class TabGalleryBox extends VBox
	{
		protected var gallery:Gallery;
		protected var galleryFilters:Vector.<GalleryFilter>;		
		protected var tabContainer:HBox;		
		protected var tabButtons:Array;
		protected var tabButtonClass:Class;
		protected var currentTab:String;
		protected var currentFilter:GalleryFilter;
		
		public var tabsBorder:Point = new Point(20,10);
		
		
		public function TabGalleryBox(gallery:Gallery, tabButtonClass:Class,  galleryFilters:Vector.<GalleryFilter>, openTab:String = "0")
		{
			super();
			this.gallery = gallery;
			this.galleryFilters = galleryFilters;
			this.tabButtonClass = tabButtonClass;
			tabContainer = new HBox();
			update();
			selectTab(openTab);
		}
		
		protected function update():void{	
			clear();
			tabContainer.clear();
			tabButtons = new Array();
			
			if(galleryFilters.length){
				addChild(tabContainer);
				for(var i:int = 0; i < galleryFilters.length; i++){
					var galleryFilter:GalleryFilter = galleryFilters[i];
					var tabButton:ButtonSelect = ButtonFactory.getButtonSelect(i.toString(), new tabButtonClass(), galleryFilter.name, selectTabHandler);
					//var tabButton:ButtonSelect = new ButtonSelect(i.toString(), new tabButtonClass(), galleryFilter.name, , selectTab);					
					tabContainer.addChild(tabButton);
					tabButtons.push(tabButton);
				}				
				addChild(gallery);
				tabContainer.x = tabsBorder.x;
				swapChildren(tabContainer, gallery);
			}else{
				addChild(gallery);
			}			
		}
		
		private function selectTabHandler(target:Button):void{
			selectTab(target.UID);
		}
		
		private function selectTab(UID:String):void{
			
			currentTab = UID;
			
			for each(var tabButton:ButtonSelect in tabButtons){
				if(tabButton.UID == currentTab){
					tabButton.Selected = true;
					currentFilter = galleryFilters[tabButton.UID];
				}else{
					tabButton.Selected = false;
				}
			}
			gallery.setSerchFilter(currentFilter);  			
		}
		
		public function selectFilter(value:GalleryFilter):void{			
			if(galleryFilters){
				for(var i:int = 0; i < galleryFilters.length; i++){
					if(galleryFilters[i].id == value.id){
						selectTab(i.toString());
						break;
					}
				}
			}
		}
		
	}
}